package org.sensation.server.operation.request.analys;

import java.io.InputStream;
import java.util.Scanner;

import org.json.JSONException;
import org.json.JSONObject;
import org.sensation.server.operation.request.OperationContext;
import org.sensation.server.operation.request.OperationRequest;

public class OperationRequestJSONAnalyst implements OperationRequestAnalys {
	private Scanner scanner;
	private OperationContext operationContext;
	
	public OperationRequest analysis(InputStream in, String hostName) throws Exception{
		setupScanner(in);
		String streamData = scanner.nextLine();
		jsonAnalysis(streamData);
		return new OperationRequest();
	}

	private void jsonAnalysis(String streamData) throws JSONException{
		JSONObject jsonObject = new JSONObject(streamData);
		generationOperationContext(jsonObject);
	}
	
	private void generationOperationContext(JSONObject jsonObject) throws JSONException {
		String[] names = JSONObject.getNames(jsonObject);
		setupOperationContext();
		for (String name : names) {
			this.operationContext.put(name, jsonObject.getString(name));
		}
	}

	private void setupOperationContext() {
		this.operationContext = new OperationContext();
	}
	private void setupScanner(InputStream in) {
		this.scanner = new Scanner(in);
	}
}
